package com.example.nnapp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener, SensorEventListener {

	private Button recordButton;
	private float x, y, z;
	private SensorManager sm;
	private Sensor acc;
	private Vibrator vibrator;
	private final float mAlpha = (float) 0.5;
	private ArrayList<Float> xEvent = new ArrayList<Float>();
	private ArrayList<Float> yEvent = new ArrayList<Float>();
	private ArrayList<Float> zEvent = new ArrayList<Float>();
	private int setNumber;
	private File file;
	private FileOutputStream f;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		acc = sm.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		
		recordButton = (Button) this.findViewById(R.id.buttonRecord);
        recordButton.setOnClickListener(this);
        
		View rootView = findViewById(R.id.rootLayout);
		rootView.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
	}

	@Override
	public void onClick(View view) {
		
		if (recordButton.getText().equals("Record")) {
			myResume();
			recordButton.setText("Recording");
		} else {
			myPause();
			recordButton.setText("Record");
		}
	}
	
	protected void myResume() {
		Log.d("AccSensor", "Called on resume");
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File (sdCard.getAbsolutePath() + "/NNApp");
		dir.mkdirs();
		Time now = new Time();
		now.setToNow();
		StringBuilder sb = new StringBuilder();
		sb.append(now.hour + "_");
		sb.append(now.minute + "_");
		sb.append(now.second + "_");
		file = new File(dir, "DataSet_" +sb.toString()+ ".txt");
		setNumber = 0;
		recordButton.setEnabled(false);
		View rootView = findViewById(R.id.rootLayout);
		rootView.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
    	try {
			f = new FileOutputStream(file, false);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		sm.registerListener(this, acc, 1000*1000);
    }

    protected void myPause() {
    	Log.d("AccSensor", "Called on pause");
    	
    	recordButton.setEnabled(true);
		View rootView = findViewById(R.id.rootLayout);
		rootView.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
		vibrator.vibrate(300);
        try {
			f.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
        sm.unregisterListener(this);
    }
    
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent sensorEvent) {
		x = sensorEvent.values[0];
		y = sensorEvent.values[1];
		z = sensorEvent.values[2];
		Log.d("AccSensor", "x=" + x + " y=" + y + " z=" + z);

		if (sensorEvent.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
			if (xEvent.size()<24) {
				// the data is read for 30 times at a 5 second set
				x = sensorEvent.values[0];
				y = sensorEvent.values[1];
				z = sensorEvent.values[2];
				xEvent.add(Math.abs(x));
				yEvent.add(Math.abs(y));
				zEvent.add(Math.abs(z));
				Log.d("AccSensor", "Added entry to set with size: "+xEvent.size());
			}
			
			if (xEvent.size() == 24) {
				setNumber++;
				adaptValuesWithHighPassFilter();
				Log.d("AccSensor", (setNumber+1) + " sets written");
				xEvent.clear();
				yEvent.clear();
				zEvent.clear();
				if (setNumber >= 30) {
					myPause();
					recordButton.setText("Record");
				}
			}	
		}
	}
	
	public float getX(){
		return x;
	}
	public float getY(){
		return y;
	}
	public float getZ(){
		return z;
	}

	private void writeToFile(String data, int i) {
	    try {
	    	f.write(data.getBytes());
	    	if (i == (xEvent.size()- 1)) {
	    	   f.write("\n".getBytes());
	    	}  
	        Log.d("AccSensor", "write to file " + i + " " + data + " ");

	    }
	    catch (IOException e) {
	        Log.e("Exception", "File write failed: " + e.toString());
	    } 
	}
	

	private void adaptValuesWithHighPassFilter() {
		if (xEvent.size() > 0) {
			writeToFile(xEvent.get(0) + " " + yEvent.get(0) + " " + zEvent.get(0) + " ", 0);
			float highZ = zEvent.get(0);
			float highX = xEvent.get(0);
			float highY = yEvent.get(0);
			for (int i = 1; i < xEvent.size(); i++) {
/*				highX = mAlpha * (highX + xEvent.get(i) - xEvent.get(i - 1));
				highY = mAlpha * (highY + yEvent.get(i) - yEvent.get(i - 1));
				highZ = mAlpha * (highZ + zEvent.get(i) - zEvent.get(i - 1));*/
				writeToFile(highX + " " + highY + " " + highZ + " ", i);
			}
		}
	}
}
